/*
 * ArCoLIVE - Live Internet Videoconference Environment
 * Information Technology Departament - Federal University of Alagoas - Brazil
 *
 * Copyright (C) 2005 Leandro Melo de Sales (leandro@labpesquisas.tci.ufal.br)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package br.ufal.tci.nexos.arcolive;

import java.lang.reflect.Constructor;
import java.util.Hashtable;
import java.util.Map;

import br.ufal.tci.nexos.arcolive.descriptors.ParticipantDescriptor;
import br.ufal.tci.nexos.arcolive.descriptors.ServiceDescriptor;
import br.ufal.tci.nexos.arcolive.descriptors.ServiceInstanceDescriptor;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVECannotAddParticipantException;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVECannotAddServiceInstanceException;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVECannotLoadServicesException;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVECannotRemoveParticipantException;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVECannotStartServiceManagerException;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVEException;
import br.ufal.tci.nexos.arcolive.exception.ArCoLIVEPersistenceException;
import br.ufal.tci.nexos.arcolive.logger.ArCoLIVELogRepository;
import br.ufal.tci.nexos.arcolive.participant.ArCoLIVEParticipant;
import br.ufal.tci.nexos.arcolive.participant.ArCoLIVEParticipantGroup;
import br.ufal.tci.nexos.arcolive.persistence.ArCoLIVEPersistence;
import br.ufal.tci.nexos.arcolive.persistence.ArCoLIVEPersistenceConnectionPoll;
import br.ufal.tci.nexos.arcolive.persistence.GenericResultSet;
import br.ufal.tci.nexos.arcolive.service.broker.ArCoLIVEServiceBroker;

/**
 * CLASSNAME.java
 *
 * CLASS DESCRIPTION
 *
 * @see CLASSNAME
 *
 * @author <a href="mailto:felipe@labpesquisas.tci.ufal.br">Felipe Barros Pontes</a>.
 * @author <a href="mailto:leandro@labpesquisas.tci.ufal.br">Leandro Melo de Sales</a>.
 * @since 0.1
 * @version 0.1
 *
 * <p><b>Revisions:</b>
 *
 * <p><b>yyyymmdd USERNAME:</b>
 * <ul>
 * <li> VERSION
 * </ul>
 */
public final class ArCoLIVEServiceManager {
	
	private static ArCoLIVEServiceManager singleton = null;
	private ArCoLIVEServicePoll servicePoll;
	private ArCoLIVEPersistenceConnectionPoll pcp;
		
	private ArCoLIVEServiceManager() throws ArCoLIVECannotStartServiceManagerException {
		this.servicePoll = new ArCoLIVEServicePoll();
		try {
			
			this.pcp = ArCoLIVEPersistenceConnectionPoll.getInstance();
			
		} catch (Exception e) {
			throw new ArCoLIVECannotStartServiceManagerException("Error while loading the Service Manager. Try to check the persistence.implementationImpl value in the configuration file"); 
		}
	}
	
	public static ArCoLIVEServiceManager getInstance() {
		if (singleton == null) {
			try {
				singleton = new ArCoLIVEServiceManager();
			} catch (ArCoLIVECannotStartServiceManagerException e) {
				return null;
			}
		}
		return singleton;
	}
	
	public void addNewServiceInstance(ArCoLIVEService service, ArCoLIVEServiceInstance serviceInstance) throws ArCoLIVECannotAddServiceInstanceException {
		this.servicePoll.addServiceInstance(service, serviceInstance);
	}
	
	public void addParticipantInService(int serviceId, int serviceInstanceId,ArCoLIVEParticipant participant) throws ArCoLIVECannotAddParticipantException {
		this.addParticipantInService(new ArCoLIVEService(serviceId), serviceInstanceId, participant);
	}
	
	public void addParticipantInService(ArCoLIVEService service, int serviceInstanceId, ArCoLIVEParticipant participant) throws ArCoLIVECannotAddParticipantException {
		ArCoLIVEServiceInstance serviceInstance = this.servicePoll.getServiceInstance(service, serviceInstanceId);		
		serviceInstance.addParticipant(participant);		
	}
	
	public void removeParticipantFromService(int serviceId, int serviceInstanceId, ArCoLIVEParticipant participant) throws ArCoLIVECannotRemoveParticipantException {
		this.removeParticipantFromService(new ArCoLIVEService(serviceId), serviceInstanceId, participant);
	}
	
	public void removeParticipantFromService(ArCoLIVEService service, int serviceInstanceId, ArCoLIVEParticipant participant) throws ArCoLIVECannotRemoveParticipantException {
		ArCoLIVEServiceInstance serviceInstance = this.servicePoll.getServiceInstance(service, serviceInstanceId);
		
		ArCoLIVEParticipantGroup participantGroup = serviceInstance.getParticipantGroup();
		
		if (participantGroup.isInParticipantGroup(participant)) {
			serviceInstance.removeParticipant(participant);
		}
		
	}
	
	public void removeParticipantFromAllService(ArCoLIVEParticipant participant) throws ArCoLIVECannotRemoveParticipantException {
		//Get all services that the participant is logged in
		ServiceDescriptor[] serviceDescriptors = this.getServiceDescriptors();
		for (int i = 0; i < serviceDescriptors.length; i++) {
			ServiceInstanceDescriptor[] serviceInstanceDescriptor = serviceDescriptors[i].getInstancesDescriptors();
			for (int j = 0; j < serviceInstanceDescriptor.length; j++) {
				this.removeParticipantFromService(serviceInstanceDescriptor[j].getServiceId(), serviceInstanceDescriptor[j].getServiceInstanceId(), participant);
			}
		}
		ArCoLIVEServiceBroker.getInstance().getParticipantGroup().removeParticipant(participant);
	}
	
	public ServiceDescriptor[] getServiceDescriptors() {
		return this.servicePoll.getServiceDescriptors();
	}
	
	public ServiceInstanceDescriptor[] getServiceInstancesDescriptors(int serviceId) {
		return this.servicePoll.getServiceInstancesDescriptors(serviceId);
	}
	
	public ParticipantDescriptor[] getParticipantDescriptors(int serviceId, int serviceInstanceId) {
		return this.servicePoll.getParticipantDescriptors(serviceId, serviceInstanceId);
	}
	
	public ArCoLIVEServiceInstance getServiceInstance(int serviceId, int serviceInstanceId) {
		return this.servicePoll.getServiceInstance(serviceId, serviceInstanceId);
	}
	
	public int statusOfService(int serviceId, int serviceInstanceId) {
		return (this.getServiceInstance(serviceId, serviceInstanceId)).getServiceStatus().getStatusId();
	}
	
	public Map loadAdditionalServiceParameters(int instanceId) {
		Map parameters = new Hashtable();
		
		try {
			ArCoLIVEPersistence persistence = pcp.getDatabaseConnection();
			GenericResultSet resultSet = persistence.getAllServiceInstanceParameter(instanceId);
			pcp.addDatabaseConnection(persistence);
			
			while (resultSet.next()) {
				String serviceParameterName = resultSet.getValue("serviceParameterName");
				String serviceParameterValue = resultSet.getValue("value");
				parameters.put(serviceParameterName, serviceParameterValue);
			}
			
			return parameters;
		} catch (ArCoLIVEPersistenceException alpe) {
			ArCoLIVELogRepository.getInstance().log("Erro when the additional parameters was loading from the database");
		}
		
		return null;
		
	}
	
	public void loadServices() throws ArCoLIVECannotLoadServicesException, ArCoLIVEPersistenceException {
		//ProtocolDescriptor protocolEnabledId[] = this.getEnabledServicesImpl();
		ArCoLIVEPersistence persistence = pcp.getDatabaseConnection();
		ArCoLIVEServiceClassPoll serviceClassPoll = ArCoLIVEServiceClassPoll.getInstance();
		GenericResultSet availableServices = persistence.getAvailableService();
		ArCoLIVELogRepository.getInstance().log("Services: ");
		while (availableServices.next()) {
			int serviceId = availableServices.getIntValue("serviceId");
			int serviceMaxInstances = availableServices.getIntValue("maxInstances");
			String serviceName = availableServices.getValue("serviceName");
			String serviceDescription = availableServices.getValue("serviceDescription");
			String classpath = availableServices.getValue("implementationClasspath");
			String protoClasspath = availableServices.getValue("protoClasspath");
			ArCoLIVEService service = new ArCoLIVEService(serviceId, protoClasspath);
			service.setName(serviceName);
			service.setDescription(serviceDescription);
			service.setMaxInstances(serviceMaxInstances);
			
			try {
				serviceClassPoll.addServiceClass(serviceName, classpath);
			} catch (ArCoLIVEException e) {
				pcp.addDatabaseConnection(persistence);
				throw new ArCoLIVECannotLoadServicesException("Erro while trying to add classpath in service class poll", e);
			}
			ArCoLIVELogRepository.getInstance().log("  - " + serviceName);
			this.servicePoll.addService(service);
			
			GenericResultSet allServiceInstance = persistence.getAllServiceInstance(serviceId, true);
			
			while (allServiceInstance.next()) {
				
				int serviceInstanceId = allServiceInstance.getIntValue("instanceId");
				Integer serviceInstanceMaxParticipant = allServiceInstance.getIntegerValue("maxParticipant");
				String serviceInstanceName = allServiceInstance.getValue("instanceName");
				String serviceInstanceDescription = allServiceInstance.getValue("instanceDescription");
				
				Class aClass = serviceClassPoll.getServiceClass(serviceName);
				Map additionalParameters = this.loadAdditionalServiceParameters(serviceInstanceId);
				
				Constructor serviceConstructor;
				try {
					serviceConstructor = aClass.getConstructor(new Class[]{int.class, int.class, String.class, String.class, int.class, Map.class});
					ArCoLIVEServiceInstance serviceInstance = (ArCoLIVEServiceInstance) serviceConstructor.newInstance(new Object[]{new Integer(serviceId), new Integer(serviceInstanceId), serviceInstanceName, serviceInstanceDescription, serviceInstanceMaxParticipant, additionalParameters});
					serviceInstance.startService();
					
					this.addNewServiceInstance(service, serviceInstance);
				} catch (Exception e) {
					ArCoLIVELogRepository.getInstance().log(e.getMessage());
					ArCoLIVELogRepository.getInstance().log(e.getMessage());
					
					pcp.addDatabaseConnection(persistence);
					throw new ArCoLIVECannotLoadServicesException("Erro while trying to construct service object from the database or an internal service start error", e);
				}

			}
			pcp.addDatabaseConnection(persistence);
			
		}

	}


}